package com.forlove.app.qselect.school.ui;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.utils.LocationUtils;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.utils.NetworkUtils;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.common.widget.recyview.BaseRecyclerAdapter;
import com.forlove.app.manager.DataManager;
import com.forlove.app.manager.NetworkManager;
import com.forlove.app.qselect.login.entity.GpsEntity;
import com.forlove.app.qselect.login.entity.SchoolDto;
import com.forlove.app.qselect.login.entity.SchoolInfoEntity;
import com.forlove.app.qselect.login.widget.SetGpsDialog;
import com.forlove.app.qselect.school.YuanxiDialog;
import com.forlove.app.qselect.school.adapter.NearbySchoolAdapter;
import com.forlove.app.qselect.school.presenter.SearchSchoolPresenter;
import com.forlove.app.qselect.school.view.SearchSchoolView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

import static com.forlove.app.qselect.login.ui.ChoiceNewAgeActivity.REQUEST_GPS;


/**
 * 搜索定位学校
 * Created by yjl on 2017/12/26.
 */
@RuntimePermissions
public class SearchSchoolActivity extends BaseActivity<SearchSchoolPresenter>
        implements SearchSchoolView, YuanxiDialog.SelectYuanxiListener {
    public static final int request_from_set_info = 20000;//从设置信息页进来
    public static final int request_from_editor_info = 20001;//从编辑个人信息页过来
    public static final int result_code_success = 1;//请求成功
    public static final int result_code_fail = 2;//请求失败
    public final int request_gps_success = 20008; //获取地理位置成功
    public final int request_gps_start = 20009; //，开始获取地理位置
    public final int request_load_school_success = 2010;//加载本地缓存的学校结束
    @BindView(R.id.list_nearby_school)
    RecyclerView list_nearby_school;

    @BindView(R.id.view_loading_nearby_school)
    LinearLayout view_loading_nearby_school;  //加载附近的学校

    @BindView(R.id.list_hot_school)
    RecyclerView list_hot_school;

    @BindView(R.id.view_loading_hot_school)
    LinearLayout view_loading_hot_school;  //加载热么学校

    @BindView(R.id.text_no_nearby_school)
    TextView text_no_nearby_school;//未找到附近的学校

    @BindView(R.id.view_nearby_school)
    LinearLayout view_nearby_school; //附近的学校

    @BindView(R.id.text_refresh_hot_school)
    TextView text_refresh_hot_school;//刷新热门学校

    @BindView(R.id.text_hot_school)
    TextView text_hot_school;    //热门学校标题

    @BindView(R.id.edittext_input_query)
    AppCompatEditText edittext_input_query;//搜索

    @BindView(R.id.image_cancel_query)
    ImageView image_cancel_query;//清楚搜索

    private SetGpsDialog setGpsDialog;
    private HandlerThread locateThread;
    private Handler loadHandler;
    private Handler mHandler;
    private AMapLocationClientOption locationOption = null;
    private AMapLocationClient locationClient = null;
    private Map<Integer, SchoolInfoEntity> schoolMap = new HashMap<>(); //学校
    private List<SchoolInfoEntity> schoolInfoEntities = new ArrayList<>();//热门学校
    private NearbySchoolAdapter hotSchoolAdapter;//热门学校
    private List<SchoolInfoEntity> searchHotSchool = new ArrayList<>();//搜索的热门学校
    private List<SchoolInfoEntity> nearbySchoolEntities = new ArrayList<>();//附近的学校列表
    private NearbySchoolAdapter nearbySchoolAdapter;//附近的学校
    private SchoolInfoEntity selectSchoolEntity; //选中的院校
    private String selectYuanxi;//选择的院系
    private YuanxiDialog yuanxiDialog;

    @Override
    public int getLayoutId() {
        return R.layout.activity_search_school;
    }

    @Override
    public void initView() {
        if (presenter == null) {
            presenter = new SearchSchoolPresenter(this);
        }
        SearchSchoolActivityPermissionsDispatcher.needLocateWithPermissionCheck(this);
        loadCacheSchool();
        initHotSchoolList();
        initNearbySchoolList();
        searchHotSchool();
    }

    @OnClick(R.id.view_back)
    public void onBack() {
        onBackPressed();
    }


    @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void needLocate() {
        getGPSLocation();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SearchSchoolActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnPermissionDenied({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void refuseLocate() {
        Toast.makeText(this, "未找到", Toast.LENGTH_SHORT).show();
        showNoNearbySchool();
    }

    @OnNeverAskAgain({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void neverAskLocate() {
        showTipDialog();
    }

    @OnClick(R.id.text_no_nearby_school)
    public void clickLoadNearbySchool() {
        //点击找不到可以重新查找
        getGPSLocation();
    }

    private void searchHotSchool() {
        edittext_input_query.setHint("输入学校名称");
        edittext_input_query.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable text) {
                searchHotSchool.clear();

                if (text != null && !TextUtils.isEmpty(text) && schoolInfoEntities.size() > 0) {
                    String searchText = text.toString().replaceAll(" ", "");
                    for (SchoolInfoEntity schoolInfoEntity : schoolInfoEntities) {
                        if (schoolInfoEntity.school.contains(searchText)) {
                            searchHotSchool.add(schoolInfoEntity);
                        }
                    }
                }
                if (searchHotSchool.size() > 0) {
                    showSearchResult();
                    hotSchoolAdapter.updateDatas(searchHotSchool);
                } else {
                    showNormalView();
                    hotSchoolAdapter.updateDatas(schoolInfoEntities);
                }
            }
        });
        image_cancel_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edittext_input_query.setText("");
                searchHotSchool.clear();
                hotSchoolAdapter.updateDatas(schoolInfoEntities);
                showNormalView();
            }
        });
    }

    private void showTipDialog() {
        if (setGpsDialog == null) {
            setGpsDialog = new SetGpsDialog(this);
            setGpsDialog.setAgreeListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, REQUEST_GPS); // 设置完成后返回到原来的界面
                }
            });
        }
        setGpsDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.e("yjl", "requestCode:" + requestCode);
        if (requestCode == REQUEST_GPS) {
            if (setGpsDialog != null) {
                setGpsDialog.dismiss();
            }
            if (requestCode == Activity.RESULT_CANCELED) {
                //拒绝授权就显示找不到
                showNoNearbySchool();
            } else {
                getGPSLocation();
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (yuanxiDialog != null) {
            yuanxiDialog.clearData();
            yuanxiDialog.dismiss();
            yuanxiDialog = null;
        }
        if (locateThread != null) {
            locateThread.quit();
            locateThread = null;
        }
        if (loadHandler != null) {
            loadHandler.removeCallbacksAndMessages(null);
            loadHandler = null;
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        if (locationClient != null) {
            locationClient.stopLocation();
        }
    }

    private void initHandler() {
        if (mHandler == null) {
            mHandler = new Handler(getMainLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == request_gps_success) {
                        //获取到gps成功
                        showLoadNearbySchool();
                        //TODO 请求接口
                        GpsEntity gpsEntity = (GpsEntity) (msg.obj);
//                        gpsEntity.lng = "31.189224";
//                        gpsEntity.lat = "121.59525";
                        requestNearbySchool(gpsEntity);
                    } else if (msg.what == request_load_school_success) {
                        //TODO 加载缓存学校成功
                        if (schoolInfoEntities.size() > 0) {
                            hotSchoolAdapter.updateDatas(schoolInfoEntities);
                            showHotSchool();
                        } else if (schoolInfoEntities.size() == 0
                                && !NetworkUtils.instance(SearchSchoolActivity.this).isNetworkAvailable()) {
                            showClickRefreshSchool();
                        }
                    } else if (msg.what == request_gps_start) {
                        showLoadNearbySchool();
                    } else {
                        //请求gps失败
                        showNoNearbySchool();
                    }
                }
            };
        }
        if (locateThread == null) {
            locateThread = new HandlerThread("loadCacheAndGetGPS");
            locateThread.start();
        }
        if (loadHandler == null) {
            loadHandler = new Handler(locateThread.getLooper());
        }
    }


    private void requestNearbySchool(GpsEntity gpsEntity) {
        Map paMap = new HashMap();
        paMap.put("lng", gpsEntity.lng);
        paMap.put("lat", gpsEntity.lat);
        presenter.loadNearbySchool(paMap);
    }

    private void getGPSLocation() {
        if (!NetworkUtils.instance(this).isNetworkAvailable()) {
            Toast.makeText(this, "请检查网络!", Toast.LENGTH_SHORT).show();
        }
        if (loadHandler == null) {
            initHandler();
        }
        showLoadNearbySchool();
        loadHandler.post(getGPSRunable);

    }

    @OnClick(R.id.text_refresh_hot_school)
    public void setTextRefreshHotSchool() {
        showLoadingHotSchool();
        presenter.loadSchoolInfo();
    }

    private void showLoadNearbySchool() {
        view_loading_nearby_school.setVisibility(View.VISIBLE);
        list_nearby_school.setVisibility(View.GONE);
        text_no_nearby_school.setVisibility(View.GONE);
    }

    private void showNoNearbySchool() {
        view_loading_nearby_school.setVisibility(View.GONE);
        list_nearby_school.setVisibility(View.GONE);
        text_no_nearby_school.setVisibility(View.VISIBLE);
    }

    private void showNearbySchool() {
        view_loading_nearby_school.setVisibility(View.GONE);
        list_nearby_school.setVisibility(View.VISIBLE);
        text_no_nearby_school.setVisibility(View.GONE);
    }

    private long time = 0;
    private Runnable getGPSRunable = new Runnable() {
        @Override
        public void run() {
            //初始化client
            if (locationClient == null) {
                locationOption = LocationUtils.getDefaultOption();
                locationClient = new AMapLocationClient(getApplicationContext());
                //设置定位参数
                locationClient.setLocationOption(locationOption);
            }
            // 设置定位监听

            locationClient.setLocationListener(new AMapLocationListener() {
                @Override
                public void onLocationChanged(AMapLocation location) {
                    synchronized (this) {
                        if (location != null) {
                            if (location.getErrorCode() == 0) {

                                LogUtil.e("yjl", "location code:" + location.getErrorCode()
                                        + "   address:" + location.getAddress());
                                //获取成功
                                GpsEntity gpsEntity = new GpsEntity();
                                gpsEntity.lng = String.valueOf(location.getLongitude());
                                gpsEntity.lat = String.valueOf(location.getLatitude());
                                DataManager.saveLocaition(SearchSchoolActivity.this, gpsEntity);
                                if (mHandler != null && System.currentTimeMillis() - time > 1000) {
                                    //至少大于1s才发送一次
                                    time = System.currentTimeMillis();
                                    Message message = new Message();
                                    message.what = request_gps_success;
                                    message.obj = gpsEntity;
                                    mHandler.sendMessage(message);
                                }
                            } else {
                                //获取gps失败
                                if (mHandler != null) {
                                    mHandler.sendEmptyMessage(location.getErrorCode());
                                }
                                LogUtil.e("yjl", "location code:" + location.getErrorCode()
                                        + "   getErrorInfo:" + location.getErrorInfo());
                            }
                        }
                    }

                }
            });
            locationClient.startLocation();
            if (mHandler != null) {
                mHandler.sendEmptyMessage(request_gps_start);
            }
        }
    };

    private void loadCacheSchool() {
        if (loadHandler == null) {
            initHandler();
        }
        loadHandler.post(new Runnable() {
            @Override
            public void run() {
                String schoolInfo = DataManager.getSchoolInfo();

                if (StringUtils.isNotEmpty(schoolInfo)) {
                    SchoolDto schoolDto = JSON.parseObject(schoolInfo, SchoolDto.class);
                    if (schoolDto != null && schoolDto.getData() != null) {
                        schoolMap.clear();
                        schoolMap.putAll(schoolDto.getData());
                    }
                }
                if (!schoolMap.isEmpty()) {
                    schoolInfoEntities.clear();
                    schoolInfoEntities.addAll(DataManager.parseSchool(schoolMap));
                }
                //获取线上最新学校
                presenter.loadSchoolInfo();
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(request_load_school_success);
                }
            }
        });
    }

    private void initHotSchoolList() {
        if (hotSchoolAdapter == null) {
            hotSchoolAdapter = new NearbySchoolAdapter(this, R.layout.item_school_name, schoolInfoEntities);
            hotSchoolAdapter.hideEmptyView();
            hotSchoolAdapter.hideFooterView();
        }
        list_hot_school.setLayoutManager(new LinearLayoutManager(this));
        list_hot_school.setAdapter(hotSchoolAdapter);
        hotSchoolAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                SchoolInfoEntity schoolInfoEntity = hotSchoolAdapter.getPositionData(position);
                if (schoolInfoEntity != null) {
                    selectSchoolEntity = new SchoolInfoEntity(schoolInfoEntity);
                    //TODO 打开院系
                    LogUtil.e("yjl", "学校：" + schoolInfoEntity.school);
                    showYuanxiDialog(schoolInfoEntity.getAcademic());
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    private void initNearbySchoolList() {
        if (nearbySchoolAdapter == null) {
            nearbySchoolAdapter = new NearbySchoolAdapter(this, R.layout.item_school_name, nearbySchoolEntities);
            nearbySchoolAdapter.hideEmptyView();
            nearbySchoolAdapter.hideFooterView();
        }
        list_nearby_school.setLayoutManager(new LinearLayoutManager(this));
        list_nearby_school.setAdapter(nearbySchoolAdapter);
        nearbySchoolAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                SchoolInfoEntity schoolInfoEntity = nearbySchoolAdapter.getPositionData(position);
                if (schoolInfoEntity != null) {
                    selectSchoolEntity = new SchoolInfoEntity(schoolInfoEntity);
                    //TODO 弹出院校弹窗
                    showYuanxiDialog(schoolInfoEntity.getAcademic());
                }
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    private void showSearchResult() {
        view_nearby_school.setVisibility(View.GONE);
        text_hot_school.setVisibility(View.GONE);
    }

    private void showNormalView() {
        view_nearby_school.setVisibility(View.VISIBLE);
        text_hot_school.setVisibility(View.VISIBLE);
    }

    private void showYuanxiDialog(List<String> yuanxi) {
        if (yuanxiDialog == null) {
            yuanxiDialog = new YuanxiDialog(this, this);
        }
        if (yuanxi.size() > 0) {
            yuanxiDialog.updateYuanxi(yuanxi);
        }
    }

    @Override
    public void selectYuanxi(String yuanxi) {
        selectYuanxi = yuanxi;
        Bundle bundle = new Bundle();
        bundle.putString("yuanxi", selectYuanxi);
        bundle.putSerializable("school", selectSchoolEntity);
        getIntent().putExtras(bundle);
        setResult(Activity.RESULT_OK, getIntent());
        finish();
    }

    private void showHotSchool() {
        list_hot_school.setVisibility(View.VISIBLE);
        view_loading_hot_school.setVisibility(View.GONE);
        text_refresh_hot_school.setVisibility(View.GONE);
    }

    private void showLoadingHotSchool() {
        list_hot_school.setVisibility(View.GONE);
        view_loading_hot_school.setVisibility(View.VISIBLE);
        text_refresh_hot_school.setVisibility(View.GONE);
    }

    private void showClickRefreshSchool() {
        list_hot_school.setVisibility(View.GONE);
        view_loading_hot_school.setVisibility(View.GONE);
        text_refresh_hot_school.setVisibility(View.VISIBLE);
    }

    @Override
    public void updateSchoolInfo(Map<Integer, SchoolInfoEntity> school) {
        if (school != null && !school.isEmpty()) {
            this.schoolMap.clear();
            this.schoolMap.putAll(school);
            schoolInfoEntities.clear();
            schoolInfoEntities.addAll(DataManager.parseSchool(this.schoolMap));
            hotSchoolAdapter.updateDatas(schoolInfoEntities);
        }
        showHotSchool();
    }

    @Override
    public void updateNearbySchool(List<SchoolInfoEntity> nearbySchool) {
        //更新附近的学校
        nearbySchoolEntities.clear();
        nearbySchoolEntities.addAll(nearbySchool);
        nearbySchoolAdapter.updateDatas(nearbySchoolEntities);
        if (nearbySchoolEntities.size() > 0) {
            showNearbySchool();
        } else {
            showNoNearbySchool();
        }
    }

    @Override
    public void showErrorData(NetworkManager.ResultCode resultCode, String msg) {
        super.showErrorData(resultCode, msg);
        if (nearbySchoolEntities.size() == 0) {
            showNoNearbySchool();
        }
        if (schoolInfoEntities.size() == 0) {
            showClickRefreshSchool();
        }
    }
}
